package com.csc531;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.csc531.edit.FriendsEdit;

public class Friends extends ListActivity
{
	private ListAdapter mAdapter;
	private static final String TAG = "MyActivity";

	//activity results
	private static final int ACTIVITY_CREATE = 0;

	//menu
	private static final int INSERT_ID = Menu.FIRST;
	private static final int DELETE_ID = Menu.FIRST + 1;


	//----------------------------------------------------------------------------------

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) 
	{
		super.onActivityResult(requestCode, resultCode, intent);
		fillFriendList();
	}

	/**
	 * Populate the friend's list
	 */
	private void fillFriendList() 
	{
		ArrayList<String> tempContacts = new ArrayList<String>();
		String classmateString = FriendsEdit.CLASSMATE_STRING;

		try 
		{
			// Get a cursor with all people
			Cursor people = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
			
			startManagingCursor(people);
			people.moveToFirst();

			do 
			{
				int notesFieldColumnIndex = people.getColumnIndex(People.NOTES);
				String contactNotesFieldContent = people.getString(notesFieldColumnIndex);

				if( contactNotesFieldContent != null && contactNotesFieldContent.contains(classmateString)) 
				{
					int nameFieldColumnIndex = people.getColumnIndex(People.NAME);
					String contact = people.getString(nameFieldColumnIndex);
					
					tempContacts.add(contact);
				}
				
			}while(people.moveToNext());
		}
		catch(CursorIndexOutOfBoundsException ex)
		{
			Log.v(TAG, "No contacts available...");
		}

	    String [] finalContacts =  new String[tempContacts.size()];
        for(int i=0 ; i < tempContacts.size(); i++)
        {
                finalContacts[i] = tempContacts.get(i);
        }
        
		mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, finalContacts);
		setListAdapter(mAdapter);		
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		super.onCreateOptionsMenu(menu);
		menu.add(0, INSERT_ID, 0, R.string.menu_insert_friend);
		menu.add(0, DELETE_ID, 0,  R.string.menu_delete_friend);

		return true;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item)
	{
		switch(item.getItemId()) 
		{
		case INSERT_ID:
			createFriend();
			return true;
		case DELETE_ID:
			deleteFriendFromApplication(getListView().getSelectedItemPosition());
			fillFriendList();
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}


	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		fillFriendList();	
	}

	/* (non-Javadoc)
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) 
	{
		super.onListItemClick(l, v, position, id);
		Intent i = new Intent(Intent.ACTION_CALL);

		String name = (String) mAdapter.getItem(position);
		Cursor cursor = getCursorInContact(name);

		int numberFieldColumnIndex = cursor.getColumnIndex(People.NUMBER_KEY);
		long phoneId = cursor.getLong(numberFieldColumnIndex);
		
		
		i.setData(Uri.parse("tel:"+reverseNumber(phoneId)));
		startActivity(i);
	}
	
	/**
	 * Reverses a number
	 * 
	 * @param number
	 * @return
	 */
	private long reverseNumber(long number)
	{
	  long reversedNumber = 0;
	  while(number != 0)
	  {
	     reversedNumber = (reversedNumber * 10) + (number % 10);
	     number /= 10;
	  }
	  return reversedNumber;
	} 


	/*
	 * Find name in Phone's contact list
	 */
	private Cursor getCursorInContact(String name) 
	{
		Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
		
		startManagingCursor(cursor);
		cursor.moveToFirst();

		do
		{
			int nameFieldColumnIndex = cursor.getColumnIndex(People.NAME);
			String contactName = cursor.getString(nameFieldColumnIndex);
			
			if( name.compareTo(contactName) == 0) 
			{
				break;
			}
			
		}while(cursor.moveToNext());

		return cursor;
	}

	/**
	 * Action method that creates a new Friend
	 */
	private void createFriend() 
	{
		Intent i = new Intent(this, FriendsEdit.class);
		startActivityForResult(i, ACTIVITY_CREATE);
	}

	/**
	 * Action method that deletes a Friend
	 */
	private void deleteFriendFromApplication(int position) 
	{
		try 
		{
			String name = (String) mAdapter.getItem(position);
			long id = getContactIdByName(name);

			Uri deleteContactUri = Uri.withAppendedPath(Contacts.People.CONTENT_URI, String.valueOf(id)); 
			Cursor people = getContentResolver().query(deleteContactUri, null, null, null, null);
			
			startManagingCursor(people);
			people.moveToFirst();
			
			int notesFieldColumnIndex = people.getColumnIndex(People.NOTES);
			String contactNotesFieldContent = people.getString(notesFieldColumnIndex);
			String cleanNotesField = contactNotesFieldContent.replace(FriendsEdit.CLASSMATE_STRING, "");

			ContentValues contactValues = new ContentValues();
			contactValues.clear();
			contactValues.put(People.NOTES,cleanNotesField);
			getContentResolver().update(deleteContactUri, contactValues, null, null);
			
			Log.v(TAG,"removed full CONTACT");
		}
		catch(IndexOutOfBoundsException ex) 
		{
			Log.v(TAG,"No contact selected...");
		}
	}

	/**
	 * Get id if a contact exists on the phone
	 * 
	 * @param name Name of the phone contact
	 * @return true if name of contact exists in phone
	 */
	private long getContactIdByName(String name) 
	{
		Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
		startManagingCursor(cursor);
		cursor.moveToFirst();

		long id = -1;
		
		do 
		{
			int nameFieldColumnIndex = cursor.getColumnIndex(People.NAME);
			String contactName = cursor.getString(nameFieldColumnIndex);
			if( name.compareTo(contactName) == 0) 
			{
				int idFieldColumnIndex = cursor.getColumnIndex(People._ID);
				id = cursor.getLong(idFieldColumnIndex);
				break;
			}
			
		}while(cursor.moveToNext());

		return id;
	}

}

